import os
import yaml
from typing import List, Dict, Any, Optional
import logging
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.schema import Document
from app.core.config import settings
from app.utils.vectorstore_client import VectorStoreClient

class ProductDocumentProcessor:
    """产品文档处理器，用于处理产品YAML内容并分块"""
    
    @staticmethod
    async def process_product_yaml(product_id: str, product_path: str) -> List[Document]:
        """
        处理产品YAML文件，将内容分块
        
        Args:
            product_id: 产品ID
            product_path: 产品文件夹路径
            
        Returns:
            List[Document]: 文档列表
        """
        try:
            # 构建YAML文件路径
            yaml_path = os.path.join(product_path, "analysis_result.yaml")
            
            if not os.path.exists(yaml_path):
                logging.warning(f"产品 {product_id} 的YAML文件不存在: {yaml_path}")
                return []
            
            # 读取YAML文件
            with open(yaml_path, 'r', encoding='utf-8') as f:
                yaml_data = yaml.safe_load(f) or {}
            
            # 提取分析结果和图片文本
            analysis_result = yaml_data.get("analysis_result", "")
            image_texts = yaml_data.get("image_texts", {})
            
            # 构建完整的文档内容
            content = f"产品ID: {product_id}\n\n"
            
            if analysis_result:
                content += f"## 分析结果\n{analysis_result}\n\n"
            
            if image_texts:
                content += "## 图片文本内容\n"
                for img_name, img_text in image_texts.items():
                    if img_text:
                        content += f"### 图片: {img_name}\n{img_text}\n\n"
            
            # 创建分块器
            text_splitter = RecursiveCharacterTextSplitter(
                chunk_size=200,
                chunk_overlap=50,
                length_function=len,
                separators=["\n\n", "\n", "。", "！", "？", ".", "!", "?", " ", ""]
            )
            
            # 分割文本
            chunks = text_splitter.split_text(content)
            
            # 创建文档对象
            documents = []
            for i, chunk in enumerate(chunks):
                doc = Document(
                    page_content=chunk,
                    metadata={
                        "product_id": product_id,
                        "chunk_id": i,
                        "source": yaml_path
                    }
                )
                documents.append(doc)
            
            logging.info(f"成功处理产品 {product_id} 的YAML文件，生成 {len(documents)} 个文档块")
            return documents
        
        except Exception as e:
            logging.error(f"处理产品YAML文件失败: {str(e)}")
            return []
    
    @staticmethod
    async def process_all_products() -> Dict[str, Any]:
        """处理所有产品的YAML文件"""
        from app.utils.file_utils import FileManager
        
        try:
            # 获取所有产品
            products = await FileManager.get_all_products()
            
            if not products:
                return {"status": "success", "message": "没有找到产品"}
            
            # 获取向量存储实例
            vector_store = VectorStoreClient.get_instance()
            
            # 处理每个产品
            processed_count = 0
            success_count = 0
            
            for product in products:
                product_id = product["id"]
                folder_path = product["folder_path"]
                
                # 处理产品YAML
                documents = await ProductDocumentProcessor.process_product_yaml(product_id, folder_path)
                
                if documents:
                    # 更新向量存储
                    store_path = os.path.join("products", product_id)
                    success, error_msg = await vector_store.update_product_vectorstore(product_id, documents, store_path)
                    
                    if success:
                        success_count += 1
                    else:
                        logging.error(f"更新产品 {product_id} 向量存储失败: {error_msg}")
                    
                    processed_count += 1
            
            return {
                "status": "success",
                "message": f"成功处理 {success_count}/{processed_count} 个产品",
                "processed_count": processed_count,
                "success_count": success_count
            }
            
        except Exception as e:
            logging.error(f"处理所有产品失败: {str(e)}")
            return {"status": "error", "message": f"处理所有产品失败: {str(e)}"}
    
    @staticmethod
    async def update_product_vectors(product_id: str) -> Dict[str, Any]:
        """更新指定产品的向量"""
        from app.utils.file_utils import FileManager
        
        try:
            # 获取产品详情
            product = await FileManager.get_product_detail(product_id)
            
            if not product or "error" in product:
                error_msg = product.get("error", "找不到产品") if product else "找不到产品"
                return {"status": "error", "message": error_msg}
            
            # 处理产品YAML
            documents = await ProductDocumentProcessor.process_product_yaml(product_id, product["folder_path"])
            
            if not documents:
                return {"status": "warning", "message": f"产品 {product_id} 没有可处理的内容"}
            
            # 更新向量存储
            vector_store = VectorStoreClient.get_instance()
            store_path = os.path.join("products", product_id)
            success, error_msg = await vector_store.update_product_vectorstore(product_id, documents, store_path)
            
            if success:
                return {"status": "success", "message": f"成功更新产品 {product_id} 的向量存储"}
            else:
                return {"status": "error", "message": f"更新向量存储失败: {error_msg}"}
            
        except Exception as e:
            logging.error(f"更新产品向量失败: {str(e)}")
            return {"status": "error", "message": f"更新产品向量失败: {str(e)}"}
    
    @staticmethod
    async def delete_product_vectors(product_id: str) -> Dict[str, Any]:
        """删除指定产品的向量"""
        try:
            # 删除向量
            vector_store = VectorStoreClient.get_instance()
            store_path = os.path.join("products", product_id)
            success = await vector_store.delete_vectorstore(store_path)
            
            if success:
                return {"status": "success", "message": f"成功删除产品 {product_id} 的向量存储"}
            else:
                return {"status": "error", "message": "删除向量存储失败"}
            
        except Exception as e:
            logging.error(f"删除产品向量失败: {str(e)}")
            return {"status": "error", "message": f"删除产品向量失败: {str(e)}"} 